<?php
namespace Admin\Controller;

use Think\PageAdmin;

/**
 * 物料管理控制器
 */
class MaterielController extends BaseController
{
    /**
     * 初始化
     * @return [type] [description]
     */
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 物料信息
     * @return [type] [description]
     */
    public function index()
    {
        $count = M('materiel')->count();
        $page = new PageAdmin($count, C('PAGE_NUM'));

        $pages['show'] = $page->show();  //分页输出
        $pages['total'] = $count;  //总数
        $pages['lists'] = M('materiel a')
            ->where(['status' => 1])
            ->order("a.id desc")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->seotitle = '物料列表';
        $this->pages = $pages;
        $this->display();
    }

    /**
     * 添加页面展示
     */
    public function add()
    {
        $this->seotitle = '添加物料';
        $this->display();
    }

    /**
     * 修改页面展示
     */
    public function upd()
    {
        $id = I('id');
        $data = M('materiel')->where(['id' => $id])->find();
        if (!$data)
            $this->error('id有误');

        $this->seotitle = '添加物料';
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 添加，修改
     */
    public function save()
    {
        $action = I('get.action', '');
        if ($action == 'add') {
            $data = I('post.');
            $data['add_time'] = time();
            $res = M('materiel')->add($data);
            if ($res) {
                $this->success('添加成功', U('index'));
            } else {
                $this->success('添加失败');
            }
        } elseif ($action == 'save') {
            $data = I('post.');
            $data['update_time'] = time();
            $res = M('materiel')->where(['id' => $data['id']])->save($data);
            if ($res) {
                $this->success('编辑成功', U('index'));
            } else {
                $this->success('编辑失败');
            }
        }
    }

    /**
     * 详情
     */
    public function detail()
    {
        $id = I('id');
        $data = M('materiel')->where(['id' => $id])->find();
        if (!$data)
            $this->error('id有误');

        $this->seotitle = '物料详情';
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 删除
     */
    public function delete()
    {
        $id = I('id');
        $info = M('materiel')->where(['id' => $id])->find();
        if ($info) {
            $rs = M('materiel')->where(['id' => $id])->save(['status' => 0, 'update_time' => time()]);
            if ($rs) {
                $this->success('删除成功', U('index'));
            } else {
                $this->error('删除失败，服务器异常');
            }
        } else {
            $this->error('删除失败，id有误');
        }
    }
}